/** Class for regression operations native to both local and global trending
 * 
 */
package trend;

import java.util.*;

/**
 * @author Hussein Patwa
 * @date 10 April 2008
 */
public class Regression {

    TreeMap getRegressionPredictions(TreeMap pathObs) {
	TreeMap rtn = new TreeMap();
	double sigmaX = sigmaX(pathObs.keySet());
	double sigmaX2 = sigmaXSquare(pathObs.keySet());
	double sigmaY = sigmaY(pathObs.values());
	double sigmaXY = sigmaXY(pathObs);
	double slope = getLeastSquareSlope(sigmaX, sigmaX2, sigmaY, sigmaXY,
		pathObs.size());// compute the slope with sign
	double constantC = getLeastSquareC(sigmaX, sigmaX2, sigmaY, sigmaXY,
		pathObs.size());
	for (Iterator i = pathObs.entrySet().iterator(); i.hasNext();) {
	    Map.Entry e = (Map.Entry) i.next();
	    Double key = (Double) e.getKey();
	    double predictedVal = slope * key.doubleValue() + constantC;
	    rtn.put(key, new Double(predictedVal));
	}
	return rtn;
    }
    
    public static double  getLeastSquareSlope(double sigX,double sigX2,double sigY,double sigXY, int N){
	    double num = ((N*sigXY) - (sigX*sigY));
	    double den = ((N*sigX2) - Math.pow(sigX,2));
	    return num/den;
	}

	public static double  getLeastSquareC(double sigX,double sigX2,double sigY,double sigXY,int N){
	    double num = ((sigX2*sigY) - (sigXY*sigX));
	    double den = ((N*sigX2) - Math.pow(sigX,2));
	    return num/den;
	}
    
}
